function createDataMFile(handles)
% createDataMFile
%
% Editing:
% gs may 2005
% gs june 2006 - improved options for used specification of file and directory 
% gs early 2008 -- various additions; removed rounding of laser power
% -----------------------------------------

% TODO: set handles.data.analysis.defaultDataMFileDir to the selected pathStr and store in handles

try
    cd(handles.data.analysis.defaultDataMFileDir);
catch
end

% specify file name and directory
exptStr = handles.data.analysis.experimentName; 
filenameDefault = [exptStr '.m'];

% use uiputfile to specify directory, with default filename from above
[fileStr, pathStr] = uiputfile(filenameDefault, 'Create data m-file:');
if fileStr == 0
%     disp('User cancelled.');
    return
end
fullFileStr = [pathStr fileStr];
% disp(['Save to: ' fullFileStr]);

% re-name the expt
[P, exptStr] = fileparts(fullFileStr);
% disp(['Ext renamed to: ' exptStr]);

% % % pathStr = uigetdir;
% % % pathStr = [pathStr '\'];
% % % fileStr = [pathStr exptStr '.m'];

% open the file for writing
fid = fopen(fullFileStr, 'w');
% TODO: store the preferred path info permanently (in a file)
% or at least for the session (in handles)

% print the first lines of the file
fprintf(fid, ['function out = ' exptStr '\n\n']);

% TODO: option to include a one-line description of the expt as a help line

% now the parameter-value pairs
fprintf(fid, ['%% ********* general info *********' '\n']);
fprintf(fid, ['map.experiment =    ''' exptStr ''';' '\n']);

% str = ['map.pathBaseName =  [''C:\\MATLAB6p5\\work\\'' map.experiment(1:end-2) ''\\traces\\''];' '\n'];
% fprintf(fid, str);
str = ['map.pathBaseName =  [''' pathStr ''' map.experiment(1:end-2) ''\traces\''];' '\n'];
s = findstr(str, '\');
v = 0 : length(s) - 1;
S = s + v;
for n = 1 : length(s) - 1 % stuff in some extra backslashes as needed for fprintf to work
    str = [str( 1 : S(n) ) '\' str( S(n) + 1 : end)];
end
fprintf(fid, str);

fprintf(fid, ['map.ampChannel =    map.experiment(end-1:end);'  '\n']);
try
    str = [datestr(datenum(handles.data.acq.breakInTime), 'ddd') ', ' datestr(datenum(handles.data.acq.breakInTime), 1)];
catch
    str = '';
end
fprintf(fid, ['map.date =          ''' str ''';'  '\n']);
fprintf(fid, ['map.sliceTime =     ''''; %% mean cutting time; 24 hour time'  '\n']);
fprintf(fid, ['map.dateVec =       [' num2str(handles.data.acq.breakInTime) '];'  '\n']);

fprintf(fid, ['%% ********* user-defined fields *********' '\n']);
fprintf(fid, ['map.exptCondition = ''' handles.data.analysis.exptCondition ''';'  '\n']);
fprintf(fid, ['map.notes =         ''' handles.data.analysis.notes ''';'  '\n']);

fieldName = handles.data.analysis.fieldAName;
fieldVal = handles.data.analysis.fieldAVal;
if isempty(fieldName)
    fieldName = 'fieldA';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldBName;
fieldVal = handles.data.analysis.fieldBVal;
if isempty(fieldName)
    fieldName = 'fieldB';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldCName;
fieldVal = handles.data.analysis.fieldCVal;
if isempty(fieldName)
    fieldName = 'fieldC';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldDName;
fieldVal = handles.data.analysis.fieldDVal;
if isempty(fieldName)
    fieldName = 'fieldD';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldEName;
fieldVal = handles.data.analysis.fieldEVal;
if isempty(fieldName)
    fieldName = 'fieldE';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldFName;
fieldVal = handles.data.analysis.fieldFVal;
if isempty(fieldName)
    fieldName = 'fieldF';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldGName;
fieldVal = handles.data.analysis.fieldGVal;
if isempty(fieldName)
    fieldName = 'fieldG';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fieldName = handles.data.analysis.fieldHName;
fieldVal = handles.data.analysis.fieldHVal;
if isempty(fieldName)
    fieldName = 'fieldH';
else
    if isnumeric(fieldName)
        fieldName = num2str(fieldName);
    end
    if isnumeric(fieldVal)
        fieldVal = num2str(fieldVal);
    end
end
str = ['map.' fieldName ' = ''' fieldVal ''';'  '\n'];
fprintf(fid, str);

fprintf(fid, ['%% ********* animal info **********' '\n']);
str = num2str(handles.data.analysis.animalAge);
fprintf(fid, ['map.age =           [' str '];'  '\n']);

fprintf(fid, ['%% ********* cell info *********' '\n']);
fprintf(fid, ['map.cellType =      ''' handles.data.analysis.cellType ''';'  '\n']);
fprintf(fid, ['map.orientation =   '''';'  '\n']);
fprintf(fid, ['map.centering =     '''';'  '\n']);
fprintf(fid, ['map.sliceXY =       []; %% how far to shift to center the slice; default is [0 0]'  '\n']);

try
    str = datestr(datenum(handles.data.acq.breakInTime), 16);

fprintf(fid, ['map.breakIn =       ''' str '''; %% 24-hr time'  '\n']);
catch
end
fprintf(fid, ['map.xy =            [' num2str(round(handles.data.acq.somaX)) '   ' num2str(round(handles.data.acq.somaY)) '];'  '\n']);
fprintf(fid, ['map.z =             [' num2str(abs(round(handles.data.acq.somaZ))) ']; %% forced to be a positive number'  '\n']);
try
    fprintf(fid, ['map.xyNew =            [' num2str(round(handles.data.acq.somaXnew)) '   ' num2str(round(handles.data.acq.somaYnew)) '];'  '\n']);
    fprintf(fid, ['map.xPatternOffset =             [' num2str(handles.data.acq.xPatternOffset) '];'  '\n']);
    fprintf(fid, ['map.yPatternOffset =             [' num2str(handles.data.acq.yPatternOffset) '];'  '\n']);
    fprintf(fid, ['map.spatialRotation =             [' num2str(handles.data.acq.spatialRotation) '];'  '\n']);
catch    
end
fprintf(fid, ['%% ********* e-phys info *********' '\n']);
fprintf(fid, ['map.sampleRate =    [' num2str(handles.data.acq.sampleRate) '];'  '\n']);
fprintf(fid, ['map.Vrest =         [' num2str(handles.data.analysis.Vrest) '];'  '\n']);
fprintf(fid, ['map.Vhold =         [' num2str(handles.data.analysis.Vhold) '];'  '\n']);
try
    fprintf(fid, ['map.Rs =            [' num2str(round(handles.data.map.mapAvg.rseriesAvg)) '];'  '\n']);
    fprintf(fid, ['map.Ri =            [' num2str(round(handles.data.map.mapAvg.rmembraneAvg)) '];'  '\n']);
    fprintf(fid, ['map.Rm =            [' num2str(round(handles.data.map.mapAvg.rmembraneAvg)) '];'  '\n']);
    fprintf(fid, ['map.Cm =            [' num2str(round(handles.data.map.mapAvg.cmembraneAvg)) '];'  '\n']);
    fprintf(fid, ['map.tau =            [' num2str(handles.data.map.mapAvg.tauAvg) '];'  '\n']);
catch
    disp('createDataMFile: problem saving cell parameters to m file.');
end

fprintf(fid, ['%% ********* video image *********' '\n']);
% TODO: option to include the image file info
fprintf(fid, ['map.imageXrange =   [' num2str(handles.data.acq.imageXrange) '];'  '\n']);
fprintf(fid, ['map.imageYrange =   [' num2str(handles.data.acq.imageYrange) '];'  '\n']);

fprintf(fid, ['%% ********* MAP DATA ********' '\n']);
switch handles.data.analysis.traceType
    case 'input map'
        
        fprintf(fid, ['map.type =          ''' handles.data.analysis.traceType '''; %% excitation profile or synaptic input map'  '\n']); % TODO: implement
        fprintf(fid, ['map.mapNumbers =    [' num2str(handles.data.analysis.mapNumbers) ']; %% vector of integers corresponding to ''m01'' etc'  '\n']); % TODO: implement
        fprintf(fid, ['map.laserPower =    [' num2str(handles.data.acq.overallAvgLaserIntensity) '];'  '\n']);
        fprintf(fid, ['map.mapSpacing =    [' num2str(round(handles.data.map.mapActive.mapSpacing)) '];'  '\n']); % TODO: improve -- get val for all maps
        fprintf(fid, ['map.stimOn =        [' num2str(handles.data.analysis.stimOn) '];'  '\n']);
        fprintf(fid, ['map.directWindow =  [' num2str(handles.data.analysis.directWindow) '];'  '\n']);
        fprintf(fid, ['map.synapticWindow = [' num2str(handles.data.analysis.synapticWindow) '];'  '\n']);
        fprintf(fid, ['map.synThreshold =  [' num2str(handles.data.analysis.synThreshold) '];'  '\n']);
        fprintf(fid, ['map.synDuration =   [' num2str(handles.data.analysis.synDuration) '];'  '\n']);

        fprintf(fid, ['map.baselineSD =    [' num2str(round(handles.data.map.mapAvg.baselineSD * 100)/100) '];'  '\n']);
        fprintf(fid, ['map.synThreshpAmV = [' num2str(round(handles.data.map.mapAvg.synThreshpAmV * 100)/100) '];'  '\n']);
        fprintf(fid, ['map.spontEventRate =[' num2str(round(handles.data.map.mapAvg.spontEventRate * 100)/100) '];'  '\n']);
        
        numCols = size(handles.data.map.mapStack.mapAvgMean, 2);
        
        fprintf(fid, ['map.genMin =         ['  '\n']);
        D = handles.data.map.mapStack.mapAvgMin';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        % sprintf(formatVec, D);
        % sprintf(['];'  '\n']);
        
        fprintf(fid, ['map.genMax =         ['  '\n']);
        D = handles.data.map.mapStack.mapAvgMax';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.genMean =        ['  '\n']);
        D = handles.data.map.mapStack.mapAvgMean';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.genOnset =       ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgOnset';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.maxOnset =       ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgMaxOnset';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.edMin =          ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgMinED';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.edMean =         ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgMeanED';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.edOnset =        ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgOnsetED';
        formatStr = '%7.4f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.eventNumSum =    ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgEventNumSum';
        formatStr = '%4.0f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        % fourth window -- mapAvgMean4th = handles.data.map.mapStack.mapAvgMean4th
        fprintf(fid, ['map.mapAvgMean4th =    ['  '\n']); 
        D = handles.data.map.mapStack.mapAvgMean4th';
        formatStr = '%8.3f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        

        try    
            fprintf(fid, ['map.directMap =         ['  '\n']); 
            D = handles.data.map.traceAvg.directMap';
            formatStr = '%7.4f ';
            formatVec = repmat(formatStr, 1, numCols);
            formatVec = ['' formatVec(1:end-1) '\n'];
            fprintf(fid, formatVec, D);
        catch
            fprintf(fid, ['];'  '\n']);
%             disp('createDataMFile: no trace-averaged directMap data found; skipping');
        end
        
        try
            fprintf(fid, ['map.nonDirectMap =         ['  '\n']); 
            D = handles.data.map.traceAvg.nonDirectMap';
            formatStr = '%7.4f ';
            formatVec = repmat(formatStr, 1, numCols);
            formatVec = ['' formatVec(1:end-1) '\n'];
            fprintf(fid, formatVec, D);
            fprintf(fid, ['];'  '\n']);
        catch
            fprintf(fid, ['];'  '\n']);
%             disp('createDataMFile: no trace-averaged nonDirectMap data found; skipping');
        end
        
    case 'excitation profile'
        
        fprintf(fid, ['map.type =          ''' handles.data.analysis.traceType '''; %% excitation profile or synaptic input map'  '\n']); % TODO: implement
        fprintf(fid, ['map.mapNumbers =    [' num2str(handles.data.analysis.mapNumbers) ']; %% vector of integers corresponding to ''m01'' etc'  '\n']); % TODO: implement
        fprintf(fid, ['map.laserPower =    [' num2str(round(handles.data.acq.overallAvgLaserIntensity)) '];'  '\n']);
        fprintf(fid, ['map.mapSpacing =    [' num2str(round(handles.data.map.mapActive.mapSpacing)) '];'  '\n']); % TODO: improve -- get val for all maps
        %         fprintf(fid, ['map.directWindow =  [' num2str(handles.data.analysis.directWindow) '];'  '\n']);
        fprintf(fid, ['map.stimOnEP =      [' num2str(handles.data.analysis.stimOnEP) '];'  '\n']);
        fprintf(fid, ['map.responseDurEP = [' num2str(handles.data.analysis.responseDurEP) '];'  '\n']);
        fprintf(fid, ['map.apThreshold =   [' num2str(round(handles.data.analysis.apThreshold)) '];'  '\n']);
        %         fprintf(fid, ['map.synDuration =   [' num2str(handles.data.analysis.synDuration) '];'  '\n']);
        
        fprintf(fid, ['map.totalNumberOfSites = [' num2str(handles.data.map.totalNumberOfSites) '];'  '\n']);
        fprintf(fid, ['map.totalNumberOfSpikes = [' num2str(handles.data.map.totalNumberOfSpikes) '];'  '\n']);

        fprintf(fid, ['map.spikesPerSite = [' num2str(handles.data.map.spikesPerSite) '];'  '\n']);
        fprintf(fid, ['map.normTotalNumberOfSpikes = [' num2str(handles.data.map.normTotalNumberOfSpikes) '];'  '\n']);
        fprintf(fid, ['map.meanWeightedDistanceFromSoma = [' num2str(handles.data.map.meanWeightedDistanceFromSoma) '];'  '\n']);
        fprintf(fid, ['map.fwhm =          [' num2str(handles.data.map.fwhm) '];'  '\n']);
        fprintf(fid, ['map.hwhm =          [' num2str(handles.data.map.hwhm) '];'  '\n']);
        
        % apDelayArray
        numCols = size(handles.data.map.mapActive.apDelayArray, 2);

        fprintf(fid, ['map.apDelayArray =  ['   '\n']);
        D = handles.data.map.mapActive.apDelayArray;
        D = D';
        formatStr = '%7.4f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        % maps
        numCols = size(handles.data.map.mapActive.mapDataArray(:,:,8), 2);
        
        fprintf(fid, ['map.apBinary =        ['  '\n']);
        D = handles.data.map.mapActive.mapDataArray(:,:,8);
        D = D';
        formatStr = '%7.1f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.apNumber =        ['  '\n']);
        D = handles.data.map.mapActive.mapDataArray(:,:,6);
        D = D';
        formatStr = '%7.1f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
        fprintf(fid, ['map.apDelay =        ['  '\n']);
        D = handles.data.map.mapActive.mapDataArray(:,:,7);
        D = D';
        formatStr = '%7.4f ';
        formatVec = repmat(formatStr, 1, numCols);
        formatVec = ['' formatVec(1:end-1) '\n'];
        fprintf(fid, formatVec, D);
        fprintf(fid, ['];'  '\n']);
        
%         disp('map.apBinary = [');
%         disp(handles.data.map.mapActive.mapDataArray(:,:,8));
%         disp('];');
%         disp('map.apNumber = [');
%         disp(handles.data.map.mapActive.mapDataArray(:,:,6));
%         disp('];');
%         disp('map.apDelay = [');
%         disp(handles.data.map.mapActive.mapDataArray(:,:,7));
    otherwise
end

fprintf(fid, 'out = map;');
status = fclose(fid);
% disp(' ');
% evalin('base', ['currentCell = ' exptStr])
disp(' ');
disp([exptStr '.m -- data M file created (or over-written) in ' pathStr]);
disp(' ');

% =====================================================================================================

% % % ********** neurolucida *********
% % map.rotation =      [];
% % map.cellDepth =     [];
% % % relative to pia:  [cell   pia    1/2    3/4    4/5A   5A/5B  5B/6   6/wm];
% % map.vertical =      []; % pia=0
% % map.XYshiftA =      [0,0]; % shift needed to center to soma;usually but not necessarily 0,0
% % map.XYshiftB =      [0,0]; % shift needed for landmark-based centering; e.g. barrel grid
% % map.nearestSeptum = '';
% % map.distToSeptum =  [];
% % map.XYshiftC =      [];
% % map.pathAndFile =   []; % ['C:\_Cartography\matlab\neurolucida\cells\' map.experiment '.mat'];
% % map.NLnotes =       '';
% % % e.g. --
% % % first give the NL ASCII file the correct g0000 type filename
% % % asciifile = importdata('C:\_Cartography\NL\L5mainly\ratL5\g0612A\g0612A.ASC', '\t');
% % % array = neurolucida2matlab(asciifile);
% % % save C:\_Cartography\matlab\neurolucida\cells\g0611.mat array
% % % load C:\_Cartography\matlab\neurolucida\cells\g0611.mat array
% % 
